package home

import (
	_ "github.com/astaxie/beego"
	_ "labix.org/v2/mgo/bson"
	"log"
	"qinnailin.cn/myblog/controllers"
	"qinnailin.cn/myblog/models"
)

type HomeController struct {
	controllers.BaseController
}

//首页
func (this *HomeController) Index() {

	article := &models.Article{}
	this.Data["alist"] = article.QueryAll()
	this.View("index")
}

//关于
func (this *HomeController) About() {
	this.View("about")
}

//注册
func (this *HomeController) Regedit() {
	this.View("regedit")
}

//注册
func (this *HomeController) DoRegedit() {
	user := &models.UserInfo{Id: models.NewObjId(), Name: this.GetString("name"),
		Password: models.Str2Md5(this.GetString("paw")),
		Email:    this.GetString("email")}

	err := user.Add()
	if err != nil {
		log.Println("注册发生错误！" + err.Error())
		this.Data["emsg"] = "注册发生错误！" + err.Error()
		this.View("regedit")
	} else if user.Id != "" {
		//this.SetSession("userinfo", user)//session 存储对象的时候发生错误
		this.Ctx.SetCookie("usertoken", user.Id)
		this.Redirect("/", 302)
	}
	return
}

//判断用户名是否存在
func (this *HomeController) UNameIsExists() {
	uname := this.GetString("Uname")
	user := &models.UserInfo{Name: uname}
	has := user.IsExists()
	if has {
		this.Ctx.WriteString("true")
	} else {
		this.Ctx.WriteString("false")
	}
	return
}

//登录
func (this *HomeController) Login() {
	this.View("login")
}

//登录
func (this *HomeController) DoLogin() {
	user := &models.UserInfo{Name: this.GetString("name"), Password: models.Str2Md5(this.GetString("paw"))}
	err := user.FindUser()
	if err != nil {
		log.Println("登录发生错误！" + err.Error())
		this.Data["emsg"] = "登录发生错误！" + err.Error()
		this.View("login")
	} else if user.Id != "" {
		//this.SetSession("userinfo", user)
		this.Ctx.SetCookie("usertoken", user.Id)
		this.Redirect("/", 302)
	}
	return
}

//登出
func (this *HomeController) LoginOut() {
	this.Ctx.SetCookie("usertoken", "")
	this.Redirect("/", 302)
}
